package com.sumfun.blog.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sumfun.blog.common.ErrorCode;
import com.sumfun.blog.exception.BusinessException;
import com.sumfun.blog.mapper.ArticleMapper;
import com.sumfun.blog.model.domain.Article;
import com.sumfun.blog.model.domain.ArticleTagReferenced;
import com.sumfun.blog.model.dto.ArticleQueryDTO;
import com.sumfun.blog.model.request.ArticleAddRequest;
import com.sumfun.blog.model.request.ArticleQueryRequest;
import com.sumfun.blog.model.request.ArticleUpdateRequest;
import com.sumfun.blog.service.ArticleService;
import com.sumfun.blog.service.ArticleTagReferencedService;
import com.sumfun.blog.service.CategoryService;
import com.sumfun.blog.service.TagService;
import com.sumfun.blog.tool.HtmlUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 超前探信息Service业务层处理
 *
 * @author linespacee
 * @date 2024-01-16
 */
@Slf4j
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService
{
    @Autowired
    private TagService tagService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ArticleTagReferencedService articleTagReferencedService;

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private ArticleCategoryReferencedServiceImpl articleCategoryReferencedService;

    public List<Article> selectList(Article t) {
        List<Article> tagNames = new ArrayList<>();
        return tagNames;
    }

    @Override
    @Transactional
    public Long addArticle(ArticleAddRequest articleAddRequest) {
        if (articleAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "Article add request is null");
        }

        // 创建文章实体并复制请求属性
        Article article = new Article();
        BeanUtils.copyProperties(articleAddRequest, article);

        // 处理文章摘要
        String summary = HtmlUtils.parseHtmlAndTruncate(article.getContentHtml(), 130);
        article.setArticleSummary(summary);

        try {
            // 插入文章并获取ID
            this.baseMapper.insert(article);
            Long articleId = article.getArticleId();
            // 获取标签ID列表
            List<Long> tagIdList = articleAddRequest.getTagIdList();
            if (tagIdList != null && !tagIdList.isEmpty()) {
                // 批量插入文章和标签的关联
                List<ArticleTagReferenced> articleTagList = tagIdList.stream()
                        .map(tagId -> {
                            ArticleTagReferenced articleTagReferenced = new ArticleTagReferenced();
                            articleTagReferenced.setArticleId(articleId);
                            articleTagReferenced.setTagId(tagId);
                            return articleTagReferenced;
                        })
                        .collect(Collectors.toList());
                articleTagReferencedService.saveBatch(articleTagList);
            }
            // 返回文章ID
            return articleId;
        } catch (Exception e) {
            // 这里可以记录日志或者进行其他异常处理
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
    }

    @Transactional
    @Override
    public boolean updateArticle(ArticleUpdateRequest articleUpdateRequest) {
        if (articleUpdateRequest == null || articleUpdateRequest.getArticleId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "Article update request cannot be null or missing ID");
        }
        Long articleId = articleUpdateRequest.getArticleId();
        // 先尝试获取文章实体
        Optional<Article> optionalArticle = Optional.ofNullable(this.getById(articleId));
        if (!optionalArticle.isPresent()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "Article not found for ID: " + articleId);
        }

        Article article = optionalArticle.get();

        // 更新文章信息
        BeanUtils.copyProperties(articleUpdateRequest, article, "id"); // 排除ID字段

        // 处理文章摘要（如果需要）
         String summary = HtmlUtils.parseHtmlAndTruncate(article.getContentHtml(), 130);
         article.setArticleSummary(summary);

        try {
            // 更新文章记录
            this.updateById(article);
            // 处理标签和分类
            if (articleUpdateRequest.getTagIdList() != null) {
                articleTagReferencedService.updateArticle(articleUpdateRequest);
            }
            if( articleUpdateRequest.getCategoryIdList() != null) {
                articleCategoryReferencedService.updateArticle(articleUpdateRequest);
            }
        } catch (Exception e) {
        }
        return true;
    }

@Override
public Page<ArticleQueryDTO> getPageList(ArticleQueryRequest articleQueryRequest) {
    IPage<Article> page = new Page<>(articleQueryRequest.getPageNum(), articleQueryRequest.getPageSize());
    IPage<Article> articleIPage = articleMapper.selectArticlesMy(page, articleQueryRequest);

    List<Article> articleList = articleIPage.getRecords();

    //添加其他项
    List<ArticleQueryDTO> articleQueryDTOList = articleList.stream()
            .map(article -> {
                ArticleQueryDTO articleQueryDTO = new ArticleQueryDTO();
                BeanUtils.copyProperties(article, articleQueryDTO); // 这里应该是article，而不是articleList
                // 获取文章标签ID列表
                List<Long> tagIds = articleTagReferencedService.getTagIdsByArticleId(article.getArticleId());
                List<String> tagNamesByIdList = tagService.getTagNamesByIdList(tagIds);
                articleQueryDTO.setTagIdList(tagIds);
                articleQueryDTO.setTagNameList(tagNamesByIdList);
                // 获取文章分类
                List<Long> categoryIds = articleCategoryReferencedService.getCategoryIdsByArticleId(article.getArticleId());
                List<String> categoryNamesByIdList = categoryService.getCategoryNamesByIdList(categoryIds);
                articleQueryDTO.setCategoryIdList(categoryIds);
                articleQueryDTO.setCategoryNameList(categoryNamesByIdList);
                
                return articleQueryDTO;
            })
            .collect(Collectors.toList());

    Page<ArticleQueryDTO> articleQueryDTOIPage = new Page<>();
    BeanUtils.copyProperties(articleIPage, articleQueryDTOIPage);
    articleQueryDTOIPage.setRecords(articleQueryDTOList);
    return articleQueryDTOIPage;
}


}
